<template>
  <el-dialog v-model="visible" title="选择商品" width="50%">
    <div class="voucherSearch">
      <el-input placeholder="请输入商品名称" clearable class="searchInputBox">
      </el-input>
    </div>
    <el-table
      ref="multipleTableRef"
      highlight-current-row
      :data="skuList"
      :row-key="
        (row: any) => {
          return row.id;
        }
      "
      @select="handleCheckBox"
      @select-all="handleSelectAll"
    >
      <el-table-column
        type="selection"
        width="50"
        align="center"
        :reserve-selection="true"
      />
      <el-table-column label="商品名称" prop="name" align="center">
      </el-table-column>
      <el-table-column label="图片" prop="pic" align="center">
        <template #default="{ row }">
          <el-image style="width: 50px; height: 50px" :src="row.pic" />
        </template>
      </el-table-column>
      <el-table-column label="属性值" prop="attribute" align="center">
        <template #default="{ row }">
          <span>{{ mergingAttributeValue(row.attribute) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="供应价" prop="supplierPrice" align="center">
      </el-table-column>
      <el-table-column label="销售价" prop="salePrice" align="center">
      </el-table-column>
      <el-table-column label="参考价" prop="referencePrice" align="center">
      </el-table-column>
      <el-table-column label="库存" prop="remained" align="center">
      </el-table-column>
    </el-table>

    <pagination
      v-if="total > 0"
      v-model:total="total"
      v-model:page="skuQueryParams.pageNum"
      v-model:limit="skuQueryParams.pageSize"
      @pagination="handleQuery"
    />

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmission">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
defineOptions({
  name: "CouponDialog",
  inheritAttrs: false,
});

defineExpose({
  open,
});

import { ref, reactive } from "vue";
import { SkuQuery, GroupSkuListVO, SkuVO } from "@/api/group/types";
import { getSkuList } from "@/api/group/index";

const emit = defineEmits(["confirm"]);

const multipleTableRef = ref();

const total = ref(0);
const skuQueryParams = reactive<SkuQuery>({
  pageNum: 1,
  pageSize: 2,
});

const skuList = ref<GroupSkuListVO[]>();

const visible = ref<boolean>(false);
const ids = ref<number[]>([]);

function open(selectIds: number[]) {
  ids.value = selectIds; //注意: 这里的ids可能分布在不同分页上

  // console.log("子 : " + selectIds);

  handleQuery();
}

function handleQuery() {
  getSkuList(skuQueryParams).then(({ data }) => {
    total.value = data.total;
    skuList.value = data.list;
    visible.value = true;
    //每次翻页后都要重新执行 选中函数, 必须放在  visible.value = true; 后， 否则第一次加载就会报 multipleTableRef.value 是 undefined ！
    nextTick(() => {
      toggleSelection();
    });
  });
}

//该方法是单选时的方法(防止分页后丢失已选中的id)
function handleCheckBox(rows: GroupSkuListVO[], row: GroupSkuListVO) {
  if (ids.value.find((id) => id == row.id)) {
    //下面这个filter方法就是删除的方法
    ids.value = ids.value.filter((id) => id != row.id);
  } else {
    ids.value.push(row.id);
  }
}

//该方法是当页全选的方法
function handleSelectAll(rows: GroupSkuListVO[]) {
  if (rows.length) {
    rows.forEach((row) => {
      if (!ids.value.find((id) => id == row.id)) {
        ids.value.push(row.id);
      }
    });
  } else {
    skuList.value!.forEach((row) => {
      ids.value = ids.value.filter((id) => id != row.id);
    });
  }
}

function handleSubmission() {
  // console.log(skuList.value);
  // console.log(ids.value);

  //处理出 选择商品后勾选选择框的数组数据
  // const selectedSkuList: SkuVO[] = skuList //有可能编辑时, ids分布在不同页面上, 但用户不点击 第二页 就在第一页上按 确定, 导致第二页的id缺失
  //   .value!.filter((item) => {
  //     const selected = ids.value.some((id) => {
  //       return id == item.id;
  //     });

  //     return selected;
  //   })
  //   .map((item) => {
  //     let skuVO: SkuVO = {
  //       skuId: item.id,
  //       name: item.name,
  //       attribute: item.attribute,
  //       pic: item.pic,
  //       prodId: item.prodId,
  //       referencePrice: item.referencePrice,
  //       remained: item.remained,
  //       salePrice: item.salePrice,
  //       supplierPrice: item.supplierPrice,
  //     };

  //     return skuVO;
  //   });

  // // console.log(selectedSkuList);

  // emit("confirm", selectedSkuList);

  emit("confirm", [...ids.value]);

  //清楚选中项目
  multipleTableRef.value!.clearSelection();
  visible.value = false;
}

function toggleSelection() {
  if (ids.value) {
    ids.value.forEach((id: number) => {
      skuList.value?.forEach((row) => {
        if (id == row.id) {
          multipleTableRef.value!.toggleRowSelection(row, true);
        }
      });
    });
  }
}
//合并sku属性值
function mergingAttributeValue(AttributeValueStr: any) {
  let AttributeValueList = JSON.parse(AttributeValueStr);
  let valueArr = [];
  for (let i = 0; i < AttributeValueList.length; i++) {
    const item = AttributeValueList[i];
    valueArr.push(Object.values(item));
  }
  return valueArr.join(",");
}
</script>

<style lang="scss" scoped>
.searchInputBox {
  width: 150px;
}

.voucherSearch {
  margin: 0 0 20px;
}
</style>
